package top.jianx.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import top.jianx.bean.Book;

import java.util.ArrayList;
import java.util.List;

/**
 * book.ftl 模板的ModelAndView页面和值同时传递方法
 */
@Controller
public class BookController {

    /**
     * 方法一：
     * book.ftl 模板的ModelAndView页面和值同时传递方法
     * 
     *  对应请求url： http://localhost:8085/books1
     * @return
     */
//    @PostMapping("/books1")
    @RequestMapping(value = "/books1", method = RequestMethod.POST)
    public ModelAndView books() {
        List<Book> books = new ArrayList<>();

        Book book1 = new Book();
        book1.setId(1);
        book1.setName("三国演义");
        book1.setAuthor("罗贯中");

        Book book2 = new Book();
        book2.setId(2);
        book2.setName("红楼梦");
        book2.setAuthor("曹雪芹");

        books.add(book1);
        books.add(book2);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("books", books);

        modelAndView.setViewName("book");

        return modelAndView;
    }

    /**方法二：
     * book.ftl 页面模板通过字符串匹配   +  model.addAttribute()传递值
     *      另： 还可以将页面和数据细分开： 先传回页面到浏览器，再异步ajax请求页面需要的数据
     *
     *  对应请求url： http://localhost:8085/books2
     * @param model
     * @return
     */
    @RequestMapping("/books2")
    public String getBookView(Model model){
        ArrayList<Book> books = new ArrayList<>();

        Book book1 = new Book();
        book1.setId(1);
        book1.setName("三国演义");
        book1.setAuthor("罗贯中");

        Book book2 = new Book();
        book2.setId(2);
        book2.setName("红楼梦");
        book2.setAuthor("曹雪芹");

        books.add(book1);
        books.add(book2);

        model.addAttribute("books", books);
        return "book";
    }
}